package com.du.web.sample.util.water;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.kernel.colors.WebColors;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @desc: pdf添加水印
 * @author: shuangdu
 * @date: 2021/9/15
 * @since: 1.8
 */
@Slf4j
public class PdfWaterMaker extends WaterMaker {

    public PdfWaterMaker(WaterMakeParam waterMakeParam) {
        super(waterMakeParam);
        this.initPdfParam();
    }

    private void initPdfParam() {
        waterMakeParam.setExtName(FileUtil.extName(waterMakeParam.getFileName()).toLowerCase());
        // 输出名称
        waterMakeParam.setOutFileName(makeOutFileName());
    }

    @Override
    public void doMake() {
        FileOutputStream outputStream = null;
        PdfWriter pdfWriter = null;
        PdfDocument pdfDocument = null;
        PdfReader pdfReader = null;
        PdfDocument readDocument = null;
        try {
            outputStream =
                    new FileOutputStream(new File("d:\\".concat(waterMakeParam.getOutFileName())));
            pdfWriter = new PdfWriter(outputStream);
            pdfDocument = new PdfDocument(pdfWriter);
            pdfReader = new PdfReader(waterMakeParam.getWaterInputStream());
            readDocument = new PdfDocument(pdfReader);
            // 添加事件
            pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, (event) -> {
                PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
                PdfDocument document = documentEvent.getDocument();
                PdfPage page = documentEvent.getPage();
                PdfFont pdfFont = null;
                try {
                    // 该字体可以正常显示中文
                    pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
//                pdfFont = PdfFontFactory.createFont("classpath:font/simhei.ttf", PdfEncodings.IDENTITY_H, false);
//                pdfFont = PdfFontFactory.createFont(FontConstants.TIMES);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Paragraph paragraph = new Paragraph(waterMakeParam.getWaterContent());

                Rectangle pageSize = page.getPageSizeWithRotation();
                float pageWidth = pageSize.getWidth();
                float pageHeight = pageSize.getHeight();

                // 添加水印文字
                PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), document);
                for (int j = 0; j < 3; j++) {
                    for (int i = 0; i < 3; i++) {
                        // 画出水印,并设置水印位置
                        new Canvas(pdfCanvas, document, page.getPageSize())
                                .setFontColor(WebColors.getRGBColor("lightgray"))
                                .setFontSize(20)
                                .setFont(pdfFont)
                                .showTextAligned(paragraph,
                                        j * pageWidth / 2,
                                        (i) * pageHeight / 2,
                                        document.getPageNumber(page),
                                        TextAlignment.CENTER,
                                        VerticalAlignment.TOP,
                                        45);
                    }
                }

                pdfCanvas.release();
            });
            //
            int number = readDocument.getNumberOfPages();
            for (int i = 1; i<= number; i++) {
                PdfPage page = readDocument.getPage(i);
                pdfDocument.addPage(page.copyTo(pdfDocument));
            }


            log.info("生成pdf路径: {}", waterMakeParam.getOutFileName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pdfDocument != null) {
                pdfDocument.close();
            }
            if (readDocument != null) {
                readDocument.close();
            }
            if (pdfReader != null) {
                try {
                    pdfReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
